package com.atqar.tongxin;
/*
多线程之间按顺序调用，实现A->B->C
三个线程启动，要求如下：

AA打印5次，BB打印10次，CC打印15次接着
AA打印5次，BB打印10次，CC打印15次
......来10轮*/


//线程 操作 资源    判断  干活  通知

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ZiYuan{
    int a=1;
    Lock lock=new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();
    public void method5(){
       lock.lock();
       try {
           //判断
           while(a!=1){
               try {
                   condition1.await();
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
           //干活
           for (int i = 1; i <= 5; i++) {
               System.out.println(Thread.currentThread().getName()+"="+i);
           }
           //通知
           a=2;
           condition2.signal();
       }finally {
           lock.unlock();
       }

    }


    public void method10(){
        lock.lock();
        try {
            //判断
            while(a!=2){
                try {
                    condition2.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            //干活
            for (int i = 1; i <= 10; i++) {
                System.out.println(Thread.currentThread().getName()+"="+i);
            }
            //通知
            a=3;
            condition3.signal();
        }finally {
            lock.unlock();
        }

    }

    public void method15(){
        lock.lock();
        try {
            //判断
            while(a!=3){
                try {
                    condition3.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            //干活
            for (int i = 1; i <= 15; i++) {
                System.out.println(Thread.currentThread().getName()+"="+i);
            }
            //通知
            a=1;
            condition1.signal();
        }finally {
            lock.unlock();
        }

    }
}



public class ProduceConsumerDemo2 {
    public static void main(String[] args) {
        ZiYuan zy = new ZiYuan();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                zy.method5();
            }
        },"a").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                zy.method10();
            }
        },"b").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                zy.method15();
            }
        },"c").start();

    }


}
